#include <stdio.h>
#include <stdlib.h>
#include "Includes/Color.h"
#include "Includes/Matrix.h"
#include "Includes/Defines.h"
#include "Includes/Rectangle.h"
#include "Includes/Surface.h"
#include "Includes/Context.h"
#include "Includes/Driver.h"
#include <unistd.h>

/// <summary>
/// TODO
/// </summary>
int GalDrawLine(Color color)
{
	return 0;
}

/// <summary>
/// TODO
/// </summary>
int GalContextFill(ContextPtr ctx, RectanglePtr rect, Color color)
{
	if (ctx == NULL)
		return -1;

	if (rect == NULL)
		return -1;

	SurfacePtr surface;
	if (!(surface = ctx->buffer))
		return -2;

	int x = /*MAX(*/rect->x/*, ctx->clip.x)*/;
	int y = /*MAX(*/rect->y/*, ctx->clip.y)*/;
	int w = /*MIN(ctx->clip.width, MIN(*/rect->width/*, surface->width))*/;
	int h = /*MIN(ctx->clip.height, MIN(*/rect->height/*, surface->height))*/;
	int s = surface->stride;
	int r = MIN((x + w), ctx->clip.width);
	int b = MIN((y + h), ctx->clip.height);

	unsigned char* data;
	if (!(data = (unsigned char*)surface->data))
		return -2;

	//data += y * s;

	int i = 0;
	int d = 0;
	for (i = y; i < b; i++)
	{
		for (d = x; d < r; d++)
		{
			//GalSetPixel(ctx, d, i, color);
			data[(i * s) + (d * 4) + 0] = 255;
			data[(i * s) + (d * 4) + 1] = 0;
			data[(i * s) + (d * 4) + 2] = 255;
			data[(i * s) + (d * 4) + 3] = 255;
		}

		//printf("y: %d\n", i);
		//data += s;
	}

	return 0;
}

/// <summary>
/// TODO
/// </summary>
int GalSetPixel(ContextPtr ctx, int x, int y, Color color)
{
	if (ctx == NULL)
		return -1;

	SurfacePtr surface;
	if (!(surface = ctx->buffer))
		return -2;

	unsigned char* data;
	if (!(data = (unsigned char*)surface->data))
		return -2;

	data += (y * surface->stride);
	data += (x * 4);
	data[0] = color.r;
	data[1] = color.g;
	data[2] = color.b;
	data[3] = color.a;

	return 0;
}

/// <summary>
/// TODO
/// </summary>
int GalBlitSurface(SurfacePtr src, SurfacePtr dst, int x, int y)
{
	if (src == NULL)
		return -1;

	if (dst == NULL)
		return -1;

	if (src->bpp != dst->bpp)
		return -2;

	return 0;
}
